//
//  ASPaginatorController.swift
//  soapp
//
//  Created by tong on 2017/7/18.
//

import UIKit

import Kingfisher
import JoLoading
import Eelay
import AsyncDisplayKit
import Alamofire

open class ASPaginatorController: ASListController,Paginator {
    open func pageResponse(task: JoTask?, response: RootData?) {
        
    }
    open var emptyLayerClass:PaginatorEmptyLayer.Type{
        get
        {
            return PaginatorEmptyLayer.defaultClass
        }
    }
    open var sections:TP.section{
        get{
            let sec:TP.section = [
                []
            ]
            return sec
        }
    }
    
    
    open var selector:TP.selector{
        get{
            let sel = TP.selector()
            assertionFailure("Must override selector:TP.selector,\(#file) \(#line)")
            //            alert("Must override selector:TP.selector")
            return sel
        }
    }
//    public var tableNode:ASTableNode = ASTableNode(style: .plain)
//    var tableView:UITableView{
//        get{
//            return tableNode.view
//        }
//    }
    public var so_constraints = [NSLayoutConstraint]()
    
//    public var page_load_section = "section0"
    
    
    
    required public init() {
        super.init()
    }
    
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    public override func load(sections:TP.section,selector:TP.selector)
    {
        tableNode.load(sections: sections, selector: selector)
    }
    
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        let vself = self
        vself.pagingScrollView = self.tableView
        self.configTables(nodes: tableNode)
        self.view.backgroundColor = UIColor.white
    }
    
    open override func refreshLinkView() {
        reload_page()
    }
    
    open func responesHandle(response:RootData?) {
        
    }
    
    open override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        
        TypeInitController.IDActiveAction(self,actionID,model)
    }
    
    
//    open override func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
//
//
//    }
//
    
    
    
    //一下三个方法与TableConfig中的扩展是一样的
    open func numberOfSections(in tableNode: ASTableNode) -> Int {
        return tableNode.sectionCount()
        
    }
    
    open func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
        let count  = tableNode.cellCount(section: section)
        
        return count
    }
    
//    open func tableNode(_ tableNode: ASTableNode, nodeBlockForRowAt indexPath: IndexPath) -> ASCellNodeBlock {
//        weak var wself = self
//        let block = tableNode.cellBlock(indexPath: indexPath, nodeBuild: {
//            node in
//            guard let ws = wself else{return}
//            if let cnode = node as? JoCellNode
//            {
//                cnode.delegate = ws
//            }
//        })
//        return block.block
//    }
    
    

    
    open override func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
        let cell = tableNode.cellNode(indexPath: indexPath, fillModel: true, delegate: self)

        cell.neverShowPlaceholders = true
        if indexPathesToBeReloaded.contains(indexPath) {
            let oldCellNode = tableNode.nodeForRow(at: indexPath)
            cell.neverShowPlaceholders = true
            oldCellNode?.neverShowPlaceholders = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                cell.neverShowPlaceholders = false
                if let indexP = self.indexPathesToBeReloaded.firstIndex(of: indexPath) {
                    self.indexPathesToBeReloaded.remove(at: indexP)
                }
            })
        }
        return cell
    }
    

    override open func reloadDataActionHappensHere(){
        let count = tableNode.dataSource?.tableNode?(tableNode, numberOfRowsInSection: 0) ?? 0
        if count > 2 {
            for row in 0...(count-1)
            {
                indexPathesToBeReloaded.append(IndexPath(row:row,section:0))
            }
        }
        
        DispatchQueue.main.async(execute: {[weak self] in
//            block(self?.hud)
            self?.tableNode.reloadData()
            self?.tableNode.waitUntilAllUpdatesAreProcessed();
            
        })
       
        
    }



    
//    @nonobjc open func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
//        let node = tableNode.cellNode(indexPath: indexPath)
//        if let jo_cell = node as? JoCellNode
//        {
//            jo_cell.content_controller = self
//            jo_cell.delegate = self
//        }
//        return node
//    }
    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    open func loadOnePage(list: [Any])->[Any] {
        return list
    }
    
    open func reload_page() {
        
//        paginator.net.cancel()

        loadMore(page: self.paginator.page_begin)//            refresh()
//        load(sections: sections, selector: selector)
//        tableNode.reloadData()
        loadingV.loading()
    }
    
    

    
    open func overseverListLoad(page:Int,sectionList:NSMutableArray)
    {
        if page == self.paginator.page_begin
        {
            sectionList.removeAllObjects()
//            loadingV.dismiss()
        }
    }
    
    //注意以下方法override 只能写在
    open func load(page: Int, succeed: Bool, list: [Any], response: RootData?, status: PageDataStatus, scrollView: UIScrollView) {
//        print("P)===========OO",succeed,status.message,paginator.net.resultTip)
        

        if page == paginator.page_begin
        {
            load(sections: sections, selector: selector)
        }
        
        let _list = self.loadOnePage(list: list)

        
        if let tab_v = scrollView as? UITableView
        {

            tab_v.backgroundView = nil

            if succeed
            {

                if let items = tableNode.model[obj:"\(page_load_section)",nil] as? NSMutableArray
                {

                    self.overseverListLoad(page: page, sectionList: items)

                    var count = items.count
                    var ps = [IndexPath]()
                    let section = sectionIndex
                    for _ in _list
                    {
                        let v = IndexPath(row: count, section: section)
                        ps.append(v)
                        count = count + 1
                    }


                    items.addObjects(from: _list)
                    switch status{
                    case .empty:
                        tab_v.backgroundView = emptyLayer
                        emptyLayer.emptyMessage = paginator.empty_msg
                 
                    case .err(let msg):
                        let tip = LoadResultType._error(tip: msg, tag: "")
                        self.loadingV.alertResult(result: tip)
//                        print("sssloadListErr|\(msg)")
                        return
                    default:
                        break
                    }

                    self.responesHandle(response: response)
                    if page == self.paginator.page_begin
                    {
                        reloadDataActionHappensHere()
                        loadingV.dismiss()
                    }
                    else
                    {
//                        self.tableNode.reloadData()
//                        tableNode.waitUntilAllUpdatesAreProcessed()
                        
                        tableNode.insertRows(at: ps, with: .top)
                    }
                }
            }
            else{
                if page == self.paginator.page_begin
                {
                    
                    self.loadingV.alertResult(result: self.paginator.net.resultTip)
//                    self.mo_request_alert(msg: "请检查网络链接是否正常".loc)
                }
            }


        }
    }
    
    open func pageRequest()
    {
        
        self.paginator.page = self.paginator.page + 1
        if paginator.page == PageConfig.page_begin
        {
            self.pagingScrollView.mj_footer?.endRefreshingWithNoMoreData()
        }
        
        if self.paginator.in_test
        {
            self.testPageRequest()
        }
        else
        {
            self.netPageRequest()
        }
        
    }

    
    open override func mo_request_alert
        (
        msg:String = "请检查网络链接是否正常".loc,
        title:String = "".loc,
        bt_title:String = "".loc
    )
    {
        weak var wself = self
        self.loadingV.handle(message: msg, title: title, button: bt_title, handAction: {
            wself?.reload_page()
            switch bt_title.escapeHeadTailSpace(){
            case "登录".loc,"立即登录".loc:
                EeAuthControl.getUser(finish_block: { (success, msg, user) in
                    
                })
            case "重试".loc,"刷新".loc:
                wself?.reload_page()
            default:
                wself?.reload_page()
            }


//            wself?.loadingV.loading()
//            wself?.loadMore(page: PageConfig.page_begin,justNow: true)
            //            wself?.refresh()
        })
       
    }


    deinit {
        self.paginator.net.cancel()
        if TypeInitController.autoClearMemoryCache
        {
            KingfisherManager.shared.cache.clearMemoryCache()
        }
        
        
    }
    
    
}




